package com.jz.banner.screen.banner.utils

import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import androidx.annotation.Nullable
import com.allenliu.versionchecklib.core.http.HttpRequestMethod
import com.allenliu.versionchecklib.v2.AllenVersionChecker
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder
import com.allenliu.versionchecklib.v2.builder.UIData
import com.allenliu.versionchecklib.v2.callback.RequestVersionListener
import com.jz.banner.screen.R
import com.jz.banner.screen.banner.bean.LaunchBean
import com.jz.banner.screen.banner.bean.UpgradeInfo
import com.jz.banner.screen.banner.net.GetApi
import com.jz.banner.screen.listener.MyUpdateCallback
import com.jz.banner.screen.ui.App
import com.jz.banner.screen.utils.ApkHelper
import com.jz.banner.screen.utils.CommUtils
import com.jz.banner.screen.utils.ShellUtils
import com.jz.banner.screen.utils.Urls
import com.king.app.updater.AppUpdater
import com.king.app.updater.http.OkHttpManager
import com.lzy.okgo.model.HttpParams
import java.util.*

object ConstantUtils {
    const val mMD5CheckOut: String = "mMD5CheckOut"
    const val app_unit_id: String = "app_unit_id"
    const val params_data: String = "params_data"
    const val c_md5: String = "c_md5"
    const val version_code: String = "version_code"
    const val upgrade_url: String = "upgrade_url"


    /*新参数*/
    fun getParams(map: SortedMap<String, Any?>): HttpParams {
        map[app_unit_id] = getAppUnitId()

        return HttpParams().apply {
            for ((key, value) in map) {
                if (value != null && value.toString().isNotBlank()) {
                    this.put(key.toString(), value.toString())
                }
            }
        }
    }

    fun getAppUnitId() = getPackageName().plus("-").plus(CommUtils.getAppUUid())

    /**
     * [获取应用程序版本名称信息]
     *
     * @return 当前应用的版本名称
     */
    @Synchronized
    fun getPackageName(): String? {
        try {
            val packageManager: PackageManager = App.context!!.packageManager
            val packageInfo: PackageInfo = packageManager.getPackageInfo(
                App.context!!.packageName, 0
            )
            return packageInfo.packageName
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    /**
     * 获取App版本码
     *
     * @return App版本码
     */
    fun getAppVersionCode(): Int {
        return CommUtils.getAppVersionCode(App.context!!, App.context!!.packageName)
    }

    fun appUpdate(versionCode: Int, url: String) {
        val context = App.context!!
        AppUpdater
            .Builder()
            .setChannelId(context.packageName)
            //.setFilename(App.context!!.getString(R.string.app_name))
            .setUrl(url)
            .setFilename(context.getString(R.string.app_name).plus(".apk"))
            .setVersionCode(versionCode)
            .build(context)
            .setHttpManager(OkHttpManager.getInstance())
            .setUpdateCallback(MyUpdateCallback())
            .start()
    }

    fun checkUpdateApp(run: Runnable = Runnable { }) {
        AllenVersionChecker.getInstance().cancelAllMission()
        var update = AllenVersionChecker
            .getInstance()
            .requestVersion()
            .setRequestUrl(GetApi.getLaunch)
            .setRequestMethod(HttpRequestMethod.POST)
            .setRequestParams(com.allenliu.versionchecklib.core.http.HttpParams().apply {
                put(app_unit_id, getAppUnitId())
            })
            .request(object : RequestVersionListener {
                @Nullable
                override fun onRequestVersionSuccess(downloadBuilder: DownloadBuilder?, result: String?): UIData? {
                    var upgradeInfo = try {
                        CommUtils.gson.fromJson(result, LaunchBean::class.java)?.data?.upgrade_info
                    } catch (e: Exception) {
                        UpgradeInfo()
                    }
                    return if (CommUtils.getAppVersionCode() < upgradeInfo?.version_code ?: 0) {
                        UIData.create()
                            .setDownloadUrl(upgradeInfo?.url)
                    } else {
                        //自动登录
                        run.run()
                        null
                    }
                }

                override fun onRequestVersionFailure(message: String) {
                    run.run()
                }
            })
            .setDownloadAPKPath(ApkHelper.getDownloadApkCachePath())
            .setApkName(App.context!!.getString(R.string.app_name))
            .setDirectDownload(true)
            .setShowNotification(true)
            .setShowDownloadingDialog(true)
            .setShowDownloadFailDialog(true)
            .setForceRedownload(false)
        when (Urls.updateType) {
            Urls.NOT_SIGN_UPDATE_TYPE_BY_SHELL_INSTALL, Urls.SIGN_UPDATE_TYPE_BY_SHELL_INSTALL_JGL -> {
                //android 6板
                update.setCustomDownloadInstallListener { context, apk ->
                    ShellUtils.execAutoRoot("/system/bin/pm install -r " + apk.path)
                }.executeMission(App.context)
            }
            Urls.NOT_SIGN_UPDATE_TYPE_BY_ANDROID_CODE_INSTALL -> {
//                    update.setCustomDownloadInstallListener { context, apk ->
//                        //android 5板
//                        var intent = Intent(Intent.ACTION_VIEW)
//                        intent.setDataAndType(apk, "application/vnd.android.package-archive")
//                        intent.putExtra("IMPLUS_INSTALL", "SILENT_INSTALL")
//                        activity.startActivity(intent)
//                    }.executeMission(App.context)
                update.executeMission(App.context)
            }
            else -> {
                update.executeMission(App.context)
            }
        }
    }
}